<!--优先购票名单页-->
<template>
    <div style="height: 100%;">
        <m-page-list
                ref="pageListRef"
                :option="option"
                :page="page"
                :total="total"
                :table-data="tableData"
                :table-loading="tableLoading"
                :page-loading="pageLoading"
                v-model:value="query"
                @h-btn-click="hBtnClick"
                @col-btn-click="colBtnClick"
                @search-data="searchData"
        >
            <template #import>
                <el-upload
                        ref="uploadRef"
                        class="upload-wrap"
                        action=""
                        accept=".xlsx,.xls"
                        :auto-upload="false"
                        :show-file-list="false"
                        :on-change="handleUploadChange"
                >
                    <el-button type="primary" >导入</el-button>
                </el-upload>
            </template>
        </m-page-list>
        <m-dialog-form ref="dialogRef" :data="dialogData" v-model:show="dialogShow" :option="dialogOption" @confirm="dialogConfirm" ></m-dialog-form>

        <!--批量生成弹窗-->
        <m-dialog-form ref="mDialogRef" :data="mDialog.data" v-model:show="mDialogShow" :option="mDialog" @confirm="handleConfirm" ></m-dialog-form>
    </div>
</template>

<script setup>
  import {ref,reactive} from 'vue'
  import * as XLSX from 'xlsx'
  //组件
  import MPageList from '@/components/PageList'
  import MDialogForm from '@/components/DialogForm/DialogForm'
  //请求
  import {getPriorityPassengers, addPriorityPassengers, editPriorityPassengers,delPriorityPassengers,batchAddPriorityPassengers,batchDelPriorityPassengers,publicPriorityPassengers,batchImportPriorityPassengers} from '@/request/api/basicData'
  import {refOpt} from "../const";
  import { readFile} from "../../utils/xlsx";
  import {getAuthority} from "../../utils/permission";

  import {usePageList} from "../../composables/pageList";

  let opts = {
    auth_id: 'EPriorityPassengers',
    getApi: getPriorityPassengers,addApi:addPriorityPassengers,editApi:editPriorityPassengers,delApi:delPriorityPassengers,
    idKey: 'row_id',
    confirmCallback: publicPriorityPassengers,
    deleteCallback: publicPriorityPassengers
  };

  let {option,page,total,tableLoading,pageLoading,tableData,query,dialogRef,dialogShow,dialogData,dialogOption,isAppend,
    newData,hBtnClick,colBtnClick,searchData,getDataList,dialogConfirm} = usePageList(opts);

  prepare()
  //开启表格选择
  // option.tableSelection = true;
  option.hLBtns = [];
  /*option.hRBtns = [
    {title: '新增',id: 'newData',type: 'primary',event: newData},
    {useSlot: true,slotName: 'import'},
    {title: '批量生成',id: 'newData',type: 'primary',event: () => handleShow('batchBuild')},
    // {title: '批量删除',id: 'newData',type: 'default',event: batchDel}
    {title: '批量删除',id: 'newData',type: 'default',event: () => handleShow('batchDel')},
  ]*/
  option.conditions = [
    {label: '乘客名称',type: 'text',field_id: 'passengers_name',col: 24},
    {...refOpt.packag_label_name,label: '套票标签',col: 12,rewriteInput: true},
    {...refOpt.school_name,col: 12,rewriteInput: true},
  ];
  option.cols = [
    {prop: 'passengers_name', label: '乘客名称',},
    {prop: 'school_name',label: '站点名称' },
    {prop: 'packag_label_name',label: '套票标签' },
    {prop: 'input_id',label: '录入员号' },
    {prop: 'input_name',label: '录入员名' },
    {prop: 'input_time',label: '录入时间' },
    {prop: 'modify_id',label: '修改员号' },
    {prop: 'modify_name',label: '修改员名' },
    {prop: 'modify_time',label: '修改时间' },
  ];
  dialogOption.fieldList = [
    {field_id: 'passengers_name',label: '乘客姓名',type: 'text',col: 3 ,required: true },
    {...refOpt.school_name,col: 3,required: true},
    {...refOpt.packag_label_name,col: 3,}
  ];

  //批量新增删除弹窗
  let dialogs = {
    batchBuild: {
      title: '批量生成',
      fieldList: [
        {...refOpt.school_name,col: 3,required: true},
        {field_id: 'effective_time_start',label: '车票有效时间起', type: 'datetime',col: 3,required: true}
      ],
      show: false,
      data: {},
    },
    batchDel: {
      title: '批量删除',
      fieldList: [
        {...refOpt.school_name,col: 3},
        {...refOpt.packag_label_name,col: 3,}
      ],
      show: false,
      data: {},

    }
  }
  let mDialog = ref({}),
    mDialogShow = ref(false),
    mDialogRef = ref(null),
    pageListRef = ref(null);

  //导入excel
  let uploadRef = ref(null)

  function handleShow(id) {
    mDialog.value = dialogs[id];
    mDialogShow.value = true;
  }
  function handleConfirm(obj) {
    let {data,option} = obj,
      title = option.title;
    new Promise(resolve => {
      if (title === '批量生成') batchAddPriorityPassengers(data).then((res) => resolve(res));
      else if (title === '批量删除') batchDelPriorityPassengers(data).then((res) => resolve(res));
    }).then((res) => {
      console.log(res);
      if (res.errcode != 0) return;
      ElMessage({
        type: 'success',
        message: `${title}成功`,
      });
      mDialogRef.value.close();
      getDataList();
      publicPriorityPassengers();
    })
  }

    //  批量删除
    function batchDel() {
      let rows = pageListRef.value.getSelectionRows();
      if (!rows.length) {
        ElMessage({type: 'warning', message: '请先选择数据行'});
        return;
      }
      ElMessageBox.confirm('确定删除所选数据？', '批量删除', {
        'cancelButtonText': '取消',
        'confirmButtonText': '确定',
        callback: (action) => {
          if (action === 'confirm'){
            pageLoading.value = true;
            let list = [];
            rows.forEach(item => {
              let {row_id} = item;
              list.push(delPriorityPassengers(row_id))
            });
            Promise.all(list).then(res => {
              pageLoading.value = false;
              let flag = true;
              res.forEach(item => {
                if (item.errcode != 0) flag = false;
              })
              flag && ElMessage({
                type: 'success',
                message: `删除成功`,
              });
              getDataList();
              publicPriorityPassengers();
            })
          }
        },
      })
    }

    const handleUploadChange = async (file) => {
      console.log(file);
      let dataBinary = await readFile(file.raw);
      let workBook = XLSX.read(dataBinary, { type: 'binary', cellDates: true })
      let workSheet = workBook.Sheets[workBook.SheetNames[0]]
      const data = XLSX.utils.sheet_to_json(workSheet);
      console.log(data);
      let list = [];
      data.forEach(item => {
        if (!item['乘车人'] || !item['站点']) return;
        list.push({
          "passengers_name": item['乘车人'] || '',
          "school_name": item['站点'] || '',
          "packag_label_name": item['套票标签'] || '',
        })
      });
      if (!list.length){
        ElMessage({
          type: 'warning',
          message: '导入数据不能为空'
        });
        return;
      }
      batchImportPriorityPassengers(list).then(res => {
        if (res.errcode != 0) return;
        ElMessage({
          type: 'success',
          message: '导入成功'
        });
        getDataList();
        publicPriorityPassengers();
      })

    }


  function prepare() {
    let arr = []

    let Bulk_import = getAuthority('Bulk_import'),
      Bulk_add2 = getAuthority('Bulk_add2'),
      Bulk_Delete= getAuthority('Bulk_Delete');


    isAppend.value && arr.push({title: '新增',id: 'newData',type: 'primary',event: newData})
    Bulk_import.is_see && arr.push({useSlot: true,slotName: 'import'})
    Bulk_add2.is_see && arr.push({title: '批量生成',id: 'newData',type: 'primary',event: () => handleShow('batchBuild')})
    Bulk_Delete.is_see && arr.push({title: '批量删除',id: 'newData',type: 'default',event: () => handleShow('batchDel')})
    option.hRBtns = arr;

  }
</script>

<style scoped lang="less">
.upload-wrap{
    display: inline-block;
    margin: 0 12px;
    vertical-align: bottom;

}
</style>
